<template>
    <article>
        <el-dialog v-model="visable" class="display-column-config-dialog" width="800px" destroy-on-close>
            <template #header>
                <span class="select-dialog-title">展示列设置</span>
            </template>
            <div class="dialog-body zw-common-scrollbar">
                <div class="select-table">
                    <div class="desc">勾选需要在列表中展示的指标</div>
                    <el-table
                        ref="selectTableRef"
                        :data="tableData"
                        height="430"
                        @select="handleSelectionChange"
                        @select-all="handleSelectionAll">
                        <el-table-column type="selection" width="55" :selectable="handleSelectable" />
                        <el-table-column label="数据列">
                            <template #default="scope">{{ scope.row.field_name }}</template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="sort-table">
                    <div class="desc">
                        已选择：
                        <span class="select-length">{{ multipleSelection.length }}</span>
                        个指标（上下拖拽顺序可调整列表列顺序）
                        <el-table id="sortTable" ref="sortTableRef" :data="multipleSelection" height="430" row-key="id">
                            <el-table-column label="展示列">
                                <template #default="scope">
                                    <span>{{ scope.row.field_name }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column width="60">
                                <template #default>
                                    <img src="@/assets/customer/sort-icon.png" class="sortImg" />
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="visable = false">取消</el-button>
                    <el-button type="primary" @click="submit">确认</el-button>
                </span>
            </template>
        </el-dialog>
    </article>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch, nextTick } from 'vue';
import type { TableInstance } from 'element-plus';
import Sortable from 'sortablejs';

import { getCommonCustomFieldList, saveCommonCustomFieldList } from '@/api/common';
import { cloneDeep } from 'lodash';

/* ----------------------------弹窗的显示与隐藏-start---------------------------- */
const props = withDefaults(
    defineProps<{
        modelValue: boolean;
        /**
         * 列的type
         * 3-客户群数据按员工
         * 4-客户群数据按群聊
         * 5-客户群数据按日期
         */
        type: number;
    }>(),
    {
        modelValue: false,
        type: 3
    }
);
const emit = defineEmits<{
    (e: 'update:modelValue', value: boolean): void;
    (e: 'submit'): void;
}>();

const visable = computed({
    get() {
        return props.modelValue;
    },
    set(value: boolean) {
        emit('update:modelValue', value);
    }
});

// 打开的情况下设置回显的数据
watch(visable, async (newVal: boolean) => {
    if (newVal) {
        await nextTick();
        getTableColumns();
    }
});
/* ----------------------------弹窗的显示与隐藏-end---------------------------- */

/* ----------------------------列表的渲染-start---------------------------- */
const selectTableRef = ref<TableInstance>();
const sortTableRef = ref<TableInstance>();
const tableData = reactive<IColumnsItem[]>([]);

const getTableColumns = async () => {
    const res: Array<IColumnsItem> = await getCommonCustomFieldList({ type: props.type });
    tableData.length = 0;
    tableData.push(...res);
    multipleSelection.value = res
        .filter(item => {
            if (item.is_select === 2) {
                selectTableRef.value?.toggleRowSelection?.(item, true);
                return true;
            }
        })
        .sort((a: IColumnsItem, b: IColumnsItem) => a.rank - b.rank);
    await nextTick();
    setSortableFun();
};
/* ----------------------------列表的渲染-end---------------------------- */

/* ----------------------------选择数据提交-start---------------------------- */
const multipleSelection = ref<IColumnsItem[]>([]);
const handleSelectionChange = (val: IColumnsItem[], row: IColumnsItem) => {
    const findIndex = multipleSelection.value.findIndex(item => item.field_key === row.field_key);
    if (findIndex > -1) {
        multipleSelection.value.splice(findIndex, 1);
    } else {
        multipleSelection.value.push(row);
    }
};

const handleSelectionAll = (val: IColumnsItem[]) => {
    multipleSelection.value = cloneDeep(val).sort((a: IColumnsItem, b: IColumnsItem) => a.rank - b.rank);
};

const handleSelectable = (row: IColumnsItem) => {
    return !(row.is_disable === 2);
};
/**
 * 选择了一些列的内容并提交
 */
const submit = async () => {
    await saveCommonCustomFieldList({
        type: props.type,
        field_config: multipleSelection.value.map(item => item.field_key)
    });

    emit('update:modelValue', false);
    emit('submit');
};
/* ----------------------------选择数据提交-end---------------------------- */

/* ----------------------------拖拽排序-start---------------------------- */
const setSortableFun = () => {
    new Sortable(document.querySelector('#sortTable')?.querySelector('.el-table__body-wrapper tbody'), {
        animation: 100,
        sort: true,
        delay: 0,
        // 拖拽元素改变位置的时候
        onUpdate(evt: any) {
            const { newIndex, oldIndex } = evt;
            const sortItem = multipleSelection.value.splice(oldIndex, 1);
            multipleSelection.value.splice(newIndex, 0, ...sortItem);
        }
    });
};
/* ----------------------------拖拽排序-end---------------------------- */

/** 选择列的参数类型 */
interface IColumnsItem {
    /** 标题 */
    field_name: string;
    /** 字段对应的key，选中后要传给后端 */
    field_key: string;
    /** 是否默认禁用, 1否，2是 */
    is_disable: 1 | 2;
    /** 是否默认选中 1否，2是 */
    is_select: 1 | 2;
    /** 排序的数字 */
    rank: number;
}
</script>
<style lang="scss" scoped>
:deep(.display-column-config-dialog) {
    .el-dialog__header {
        padding: 20px 24px;
        font-size: 16px;
        font-family: PingFangSC-Medium, 'PingFang SC';
        font-weight: 500;
        color: #33302d;
        line-height: 16px;
    }

    .el-dialog__body {
        padding: 0;
    }

    .dialog-body {
        display: flex;
        overflow-y: auto;
        height: 522px;
        box-sizing: border-box;
        padding: 24px;

        > div {
            flex: 1;
        }
    }

    .select-table {
        position: relative;
        padding-right: 20px;

        &::after {
            content: '';
            position: absolute;
            top: 50px;
            right: 0;
            width: 1px;
            height: calc(100% - 50px);
            background: #f4f4f4;
            border-radius: 3px;
        }
    }

    .sort-table {
        box-sizing: border-box;
        padding: 0 6px 0 30px;

        .el-table__row {
            cursor: grab;
        }
    }

    .select-dialog-icon {
        margin-left: 4px;
        vertical-align: top;
    }

    .desc {
        font-size: 14px;
        font-family: PingFangSC-Regular, 'PingFang SC';
        font-weight: 400;
        color: #33302d;
        line-height: 20px;

        .select-length {
            color: #ff6b00;
        }
    }

    .el-table {
        margin-top: 16px;

        thead tr th {
            background: #f9f9f9;
        }
    }

    .sortImg {
        width: 12px;
        height: 12px;
    }
}
</style>
